package com.gdkj.tencent;

import com.alibaba.fastjson.JSONObject;
import com.gdkj.common.LogicResult;
import com.gdkj.constant.CommonConstant;
import com.gdkj.enums.IMMessageTypeEnums;
import com.gdkj.params.ImUserInfo;
import com.google.common.collect.Lists;
import com.xjgks.common.exception.handler.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.Instant;
import java.util.*;

@Service
@Slf4j
public class ImService implements IIm {

    @Autowired
    private ImApi imApi;

    /**
     * 销毁群组
     * @param groupId
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult destroyGroup(String groupId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", groupId);
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_COMMAND_DESTROY_GROUP);
    }
    
    
    /**
    * 注册用户
    */
    @Override
    public LogicResult addUser(String userId,String nick,String faceUrl) throws Exception{
        Map<String, Object> info = new HashMap<>();
        //id规范（客户：C+电话号码，管理员：M+电话号码，客服：S+电话号码）
        info.put("Identifier", userId);
        //有昵称用昵称，无则为用户名
        info.put("Nick", nick);
        info.put("FaceUrl", faceUrl);
        JSONObject jsonObject = imApi.toPost("/v4/im_open_login_svc/account_import", info);
        if (jsonObject.get("ActionStatus").equals("FAIL")) {
            log.error("im注册用户失败：" + jsonObject.get("ErrorCode") + ":" + jsonObject.get("ErrorInfo"));
            throw new RRException("im注册用户失败");
        }
        if (jsonObject.get("ActionStatus").equals("OK")) {
            return LogicResult.success();
        }
        return LogicResult.success();
    }

    /**
     * 创建群组
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult createGroupWithNoGroupId(Long uid) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Type", "AVChatRoom");
//        jsonObject.put("Type", "Public");
        jsonObject.put("Name", "name" + uid);
        jsonObject.put("ApplyJoinOption", "FreeAccess");
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_COMMAND_CREATE_GROUP);
    }

    /**
     * 创建群组
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public LogicResult createGroup(Long uid) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Owner_Account", String.format("%d", uid));
        jsonObject.put("Type", "AVChatRoom");
//        jsonObject.put("Type", "Public");
        jsonObject.put("Name", "name" + uid);
        jsonObject.put("ApplyJoinOption", "FreeAccess");
        jsonObject.put("GroupId", String.format("%d", uid));
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_COMMAND_CREATE_GROUP);
    }

    /**
     * 创建群组
     * @param groupId groupId
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult createGroup(String groupId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Owner_Account", groupId);
        jsonObject.put("Type", "AVChatRoom");
//        jsonObject.put("Type", "Public");
        jsonObject.put("Name", "name" + groupId);
        jsonObject.put("ApplyJoinOption", "FreeAccess");
        jsonObject.put("GroupId", groupId);
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_COMMAND_CREATE_GROUP);
    }

    /**
     * 创建群组
     * @param groupId groupId
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult createGroup(Long uid, String groupId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (uid != null) {
            jsonObject.put("Owner_Account", String.format("%d", uid));
        }
        jsonObject.put("Type", "ChatRoom");
//        jsonObject.put("Type", "Public");
        jsonObject.put("Name", "name" + groupId);
        jsonObject.put("ApplyJoinOption", "FreeAccess");
        jsonObject.put("GroupId", groupId);
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_COMMAND_CREATE_GROUP);
    }

    /**
     * 发送普通消息
     * @param data
     * @param groupId
     * @return LogicResult
     */
    @Override
    public LogicResult sendNormalGroupMessage(String data, String groupId) throws Exception {
        IMBody imBody = new IMBody();
        imBody.setGroupId(groupId);
        Random random = new Random();
        imBody.setRandom(random.nextInt(9999999));
        List<IMMessageBody> msgBody = new ArrayList<>();
        IMMessageBody imMessageBody = new IMMessageBody();
        imMessageBody.setMsgType(IMMessageTypeEnums.TEXT.getName());
        ImMsgContent msgContent = new ImMsgContent();
        msgContent.setText(data);
        imMessageBody.setMsgContent(msgContent);
        msgBody.add(imMessageBody);
        imBody.setMsgBody(msgBody);
        return imApi.send(imBody, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_SEND_GROUP_MESSAGE);
    }

    /**
     * 发送系统通知
     * @param groupId
     * @param data
     * @return LogicResult
     */
    @Override
    public LogicResult sendSystemNotification(String data, String groupId) throws Exception {
        IMSysNotifyBody imSysNotifyBody = new IMSysNotifyBody();
        imSysNotifyBody.setGroupId(groupId);
        imSysNotifyBody.setContent(data);
        return imApi.send(imSysNotifyBody, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_SEND_SYSTEM_NOTIFY);
    }

    /**
     * 发送单聊消息
     * @param uid
     * @param content
     * @return LogicResult
     */
    @Override
    public LogicResult sendSingleMessage(Long uid, String content) throws Exception {
        IMSingleMessageBase imSingleMessageBase = new IMSingleMessageBase();
        imSingleMessageBase.setToAccount(uid.toString());
        imSingleMessageBase.setSyncOtherMachine(2);
        Random random = new Random();
        imSingleMessageBase.setMsgRandom(random.nextInt(9999999));
        Instant instant = Instant.now();
        imSingleMessageBase.setMsgTimeStamp(instant.getEpochSecond());
        List<String> controlOptions = Lists.newArrayList();
        controlOptions.add("ForbidBeforeSendMsgCallback");
        controlOptions.add("ForbidAfterSendMsgCallback");
        imSingleMessageBase.setForbidCallbackControl(controlOptions);
        List<IMMsgBody> msgBodyList = new ArrayList<>();
        IMMsgBody imMsgBody = new IMMsgBody();
        imMsgBody.setMsgType(IMMessageTypeEnums.CUSTOM.getName());
        ImCustomMsgContent imCustomMsgContent = new ImCustomMsgContent();
        imCustomMsgContent.setData(content);
        imMsgBody.setMsgContent(imCustomMsgContent);
        msgBodyList.add(imMsgBody);
        imSingleMessageBase.setMsgBody(msgBodyList);
        return imApi.send(imSingleMessageBase, CommonConstant.IM_SERVICE_NAME_SINGLE, CommonConstant.IM_SEND_TO_SINGLE);
    }
    
    
    /**
    * 资料设置
    */
    @Override
    public Boolean settingInfo(ImUserInfo po) throws UnsupportedEncodingException {
        Map<String, Object> info = new HashMap<>();
        info.put("From_Account", po.getAccount());
        List<HashMap<String, String>> ProfileItem = new ArrayList<>();
        if (po.getTag_Profile_IM_AllowType() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_AllowType");
            item.put("Value", po.getTag_Profile_IM_AllowType());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_Gender() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_Gender");
            item.put("Value", po.getTag_Profile_IM_Gender());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_Image() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_Image");
            item.put("Value", po.getTag_Profile_IM_Image());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_MsgSettings() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_MsgSettings");
            item.put("Value", po.getTag_Profile_IM_MsgSettings());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_Nick() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_Nick");
            item.put("Value", po.getTag_Profile_IM_Nick());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_Role() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_Role");
            item.put("Value", po.getTag_Profile_IM_Role());
            ProfileItem.add(item);
        }
        if (po.getTag_Profile_IM_SelfSignature() != null) {
            HashMap<String, String> item = new HashMap<>();
            item.put("Tag", "Tag_Profile_IM_SelfSignature");
            item.put("Value", po.getTag_Profile_IM_SelfSignature());
            ProfileItem.add(item);
        }
        info.put("ProfileItem", ProfileItem);
        JSONObject jsonObject = imApi.toPost("/v4/profile/portrait_set", info);
        if (jsonObject.get("ActionStatus").equals("FAIL")) {
            log.error("IM修改资料失败：" + jsonObject.get("ErrorCode") + ":" + jsonObject.get("ErrorInfo"));
            return false;
        }
        if (jsonObject.get("ActionStatus").equals("OK")) {
            log.info("IM修改资料：" + po.getAccount() + "成功");
            return true;
        }
        return true;
    }

    /**
     * 移除im
     * @param groupId groupId
     * @param accountList accountList
     * @return LogicResult
     */
    public LogicResult deleteGroupMember(String groupId, List<String> accountList) throws Exception {
        IMGroupRemoveUserRequest imGroupRemoveUserRequest = new IMGroupRemoveUserRequest();
        imGroupRemoveUserRequest.setGroupId(groupId);
        imGroupRemoveUserRequest.setSilence(1);
        imGroupRemoveUserRequest.setMemberToDelAccounts(accountList);
        return imApi.send(imGroupRemoveUserRequest, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_DELETE_GROUP_MEMBER);
    }

    /**
     * 获取群组信息
     * @param groupIdList groupIdList
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult getGroupInfo(List<String> groupIdList) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupIdList", groupIdList);
        return imApi.send(jsonObject, CommonConstant.IM_SERVICE_NAME, CommonConstant.IM_GET_GROUP_INFO);
    }

    /**
     * 批量导入账户
     * @param accountIdList
     * @return LogicResult
     * @throws Exception
     */
    @Override
    public LogicResult batchImportAccount(List<String> accountIdList) throws Exception {
        return null;
    }

    /**
     * 全员推送消息
     * @param content
     * @return LogicResult
     */
    @Override
    public LogicResult sendAllMessage(String content) throws Exception {
        IMAllMessageBase imAllMessageBase = new IMAllMessageBase();
        imAllMessageBase.setFromAccount(CommonConstant.ADMIN);
        Random random = new Random();
        imAllMessageBase.setMsgRandom(random.nextInt(9999999));

        List<IMMsgBody> msgBodyList = new ArrayList<>();
        IMMsgBody imMsgBody = new IMMsgBody();
        imMsgBody.setMsgType(IMMessageTypeEnums.CUSTOM.getName());
        ImCustomMsgContent imCustomMsgContent = new ImCustomMsgContent();
        imCustomMsgContent.setData(content);
        imMsgBody.setMsgContent(imCustomMsgContent);
        msgBodyList.add(imMsgBody);
        imAllMessageBase.setMsgBody(msgBodyList);
        return imApi.send(imAllMessageBase, CommonConstant.IM_ALL_PUSH_SERVICE_NAME, CommonConstant.IM_ALL_PUSH_SERVICE_NAME_SINGLE);
    }
}
